/**
 * @Author: wangjian
 * 656876071@qq.com
 * @Date: 2024-07-22 17:14:05
 * @LastEditTime: 2024-09-11 16:22:59
 * @FilePath: src/core/utils/request.ts
 * @Description:
 */
import axios, {type AxiosRequestConfig} from "axios";
import {message} from "ant-design-vue";
import useRouter from "@/router";


export const TOKEN_KEY = "_TOKEN_"

const axiosConfig: AxiosRequestConfig = {

    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 10s
    timeout: 10000,
    headers: {
        "Content-Type": "application/json;charset=UTF-8",
    },
    // 跨域请求时是否携带cookie
    withCredentials: true,

}

const instance = axios.create(axiosConfig)

// Add a request interceptor
instance.interceptors.request.use(function (config) {
    // Do something before request is sent
    let token = localStorage.getItem(TOKEN_KEY)
    if (!token) {
        message.error("没有令牌")
        throw {message: "token is null", response: {code: 401}}
    }
    config.headers["SA-TOKEN"] = `${token}`
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
}, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    if (error.response && error.response.status == 401) {
        const router = useRouter()
        localStorage.removeItem(TOKEN_KEY)
        message.error("令牌失效")
        router.push("/login")
    }
    return Promise.reject(error);
});

interface Ret {
    code: number,
    msg: string,
    data: any
}

export default instance
export type {Ret}